package com.feihong.yw189.fragment.shouye;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.FloatRange;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.feihong.yw189.R;
import com.feihong.yw189.activity.WebInterface.AjaxWebInterface;
import com.feihong.yw189.activity.WebInterface.OrderWebInterface;
import com.feihong.yw189.activity.dingdan.DingDanDetailsActivity;
import com.feihong.yw189.fragment.base.BaseFragment;
import com.feihong.yw189.http.HttpTools;
import com.feihong.yw189.http.RefreshToken;
import com.feihong.yw189.utils.MyLoginUtils;
import com.feihong.yw189.utils.ToolsUtil;
import com.feihong.yw189.utils.UserLoginInfo;
import com.feihong.yw189.utils.WebViewClientRToken;
import com.feihong.yw189.view.WebView4Scroll;
import com.just.agentweb.AgentWeb;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Sabirjan on 2017/11/13.
 * DX189.
 * 飞宏电子
 * 首页---->订单列表页面
 */

@SuppressLint("ValidFragment")
public class DingDanLieBiaoFragment extends BaseFragment {

    RelativeLayout webviewFrame;
    private SwipeRefreshLayout mswiperefreshlayout;
    public AgentWeb.PreAgentWeb preAgentWeb;
    public AgentWeb mAgentWeb;

    RelativeLayout mBackLayout;
    TextView mTitltView;
    public static DingDanLieBiaoFragment newInstance(String tabName) {
        DingDanLieBiaoFragment dingDanLieBiaoFragment = new DingDanLieBiaoFragment();
        dingDanLieBiaoFragment.tag = tabName;
        return dingDanLieBiaoFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentView = inflater.inflate(R.layout.fragment_webview, container, false);
        mBackLayout = fragmentView.findViewById(R.id.rl_goback);
        mBackLayout.setVisibility(View.GONE);
        mTitltView = fragmentView.findViewById(R.id.txt_pagetitle);
        mTitltView.setText("订单");
        return fragmentView;
    }

    @Override
    protected void setTheme() {
    }


    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);

        //绑定View
        initView();
    }


    @Override
    public void initView() {
        setPageTitle("订单");
        webviewFrame = (RelativeLayout) findView(R.id.webviewframe);

        // AgentWeb 保持了 WebView 的使用 ，
        mswiperefreshlayout = (SwipeRefreshLayout) findView(R.id.swiperefreshlayout);
        //设置刷新时动画的颜色，可以设置4个
        mswiperefreshlayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        mswiperefreshlayout.setColorSchemeResources(R.color.appRed,
                android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);

        mswiperefreshlayout.setOnRefreshListener(() -> bindData());

        if (preAgentWeb == null) {
            WebView4Scroll webView4Scroll = new WebView4Scroll(getActivity(), mswiperefreshlayout);
            webView4Scroll.setVerticalScrollBarEnabled(false);
            preAgentWeb = AgentWeb.with(this)
                    .setAgentWebParent(webviewFrame, new RelativeLayout.LayoutParams(-1, -1))
                    .useDefaultIndicator()
                    .setWebView(webView4Scroll)
                    .setWebViewClient(webViewClient)
                    .setMainFrameErrorView(R.layout.agentweb_errorlayout, R.id.agentweb_re_query_data_layout)
                    .createAgentWeb()
                    .ready();
        }
        bindData();
    }
    //WebChromeClient
    private WebChromeClient mWebChromeClient = new WebChromeClient() {

    };
    @Override
    public void bindData() {

        mAgentWeb = preAgentWeb.go(HttpTools.ORDER_LIST_PAGE + "?token="+UserLoginInfo.getUserLoginInfoInstance().getUserToken()+"&version="+"and." + AppUtils.getAppVersionName());
        mAgentWeb.getAgentWebSettings().getWebSettings().setGeolocationEnabled(false);
        jsCallJava();

        //屏蔽长按弹出复制按钮
  /*      mAgentWeb.getWebCreator().get().setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });*/

    }

    private void jsCallJava() {

        //添加Ajax数据请求的接口
        mAgentWeb.getJsInterfaceHolder().addJavaObject(AjaxWebInterface.AJAX_KEY, new AjaxWebInterface(_mActivity, mAgentWeb.getJsAccessEntrace()));

        mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new OrderWebInterface(mAgentWeb, _mActivity, new ActionCallBack() {
            @Override
            public String getToken() {
                String token = UserLoginInfo.getUserLoginInfoInstance().getUserToken();
                return token;
            }

            @Override
            public boolean setToken(String info) {
                if (info != null && !info.isEmpty()) {
                    return RefreshToken.getInstance().RefreshToken(info);
                } else {
                    return false;
                }
            }

            @Override
            public String sendSign(String info) {
                try {
                    JSONObject json = new JSONObject();
                    Map<String, String> map = new HashMap<>();
                    long time = MyLoginUtils.getCuurrentTime();
                    map.put("time", "" + time);
                    json.put("sign", "" + ToolsUtil.getsignRes(info, map));
                    json.put("time", TimeUtils.getNowMills() / 1000 + "");
                    return json.toString();
                } catch (Exception e) {
                    e.printStackTrace();
                    return "error";
                }
            }

            @Override
            public String getOrderSn() {
                return "";
            }

            @Override
            public Boolean toOrderInfo(String info) {
                try {
                    Log.i(TAG, "toOrderInfo: " + info);
                    JSONObject jsonObject = new JSONObject(info);
                    String order_info = jsonObject.optString("order_info");
                    String order_sn = jsonObject.optString("order_sn");
                    String title = jsonObject.optString("title");

                    Intent mInetent = new Intent();
                    mInetent.setClass(getActivity(), DingDanDetailsActivity.class);
                    mInetent.putExtra("orderInfo", order_info);
                    mInetent.putExtra("order_sn", order_sn);
                    mInetent.putExtra("title", title);
                    startActivity(mInetent);
                } catch (Exception e) {
                }
                return false;
            }
        }));
    }

    private WebViewClient webViewClient = new WebViewClientRToken() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return true;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (mswiperefreshlayout != null) {
                mswiperefreshlayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mswiperefreshlayout.setRefreshing(false);
                    }
                }, 300);
            }
            mswiperefreshlayout.setRefreshing(false);
        }
    };

    @Override
    public void onDestroy() {
        try {
            if (mAgentWeb != null) {
                mAgentWeb.destroy();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        super.onDestroy();
    }

    public interface ActionCallBack {
        public String getToken();

        public boolean setToken(String info);

        public String sendSign(String info);

        public String getOrderSn();

        public Boolean toOrderInfo(String info);

    }

    //Activity里面判断返回键
    public boolean canGoBack() {

        if (mAgentWeb != null && mAgentWeb.getWebCreator().getWebView().canGoBack()) {

            mAgentWeb.getWebCreator().getWebView().goBack();
            return false;
        }
        return true;
    }

    @Override
    public boolean onBackPressedSupport() {
        return canGoBack();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onResume();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onDestroy();
        }
    }

      public boolean isMobileConnected(Context context) {
            if (context != null) {
                     ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                             .getSystemService(Context.CONNECTIVITY_SERVICE);
                     NetworkInfo mMobileNetworkInfo = mConnectivityManager
                             .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                     if (mMobileNetworkInfo != null) {
                             return mMobileNetworkInfo.isAvailable();
                         }
                 }
             return false;
         }

}
